package handle

import (
	"duanju-mq/db"
	"duanju-mq/pkg/formatStruct"
	"duanju-mq/pkg/log"
	"duanju-mq/pkg/util/convert"
	"encoding/json"
	"fmt"
	"net/url"
)

type promotionLinkStatistics struct {
	LinkCode          string `json:"link_code" field:"link_code"`
	DownloadTotal     int64  `json:"download_total" field:"download_total"`
	ClickTotal        int64  `json:"click_total" field:"click_total"`
	RegisterTotal     int64  `json:"register_total" field:"register_total"`
	RechargeUserCount int64  `json:"recharge_user_count" field:"recharge_user_count"`
	RechargeAmount    int64  `json:"recharge_amount" field:"recharge_amount"`
	RechargeCount     int64  `json:"recharge_count" field:"recharge_count"`
	Date              int64  `json:"date" field:"date"` //日期0点时间戳
	CreateAt          int64  `json:"create_at" field:"create_at"`
	UpdatedAt         int64  `json:"updated_at" field:"updated_at"`
}

func HandlePromotionLink(rawData string) {

	info := &promotionLinkStatistics{}
	if err := json.Unmarshal([]byte(rawData), info); err != nil {
		log.Err(fmt.Sprintf("HandlePromotionLink json.Unmarshal value:%v err:%+v", rawData, err))
		return
	}

	var (
		parseData = formatStruct.ParseStructFields(info)

		cond = fmt.Sprintf(`ON DUPLICATE KEY UPDATE 
			register_total=register_total+?,
			download_total=download_total+?,
			click_total=click_total+?,
			recharge_amount=recharge_amount+?,
			recharge_count=recharge_count+?,
			updated_at=?`)
	)

	data := url.Values{}
	data.Set("link_code", info.LinkCode)
	data.Set("download_total", convert.ToString(info.DownloadTotal))
	data.Set("click_total", convert.ToString(info.ClickTotal))
	data.Set("register_total", convert.ToString(info.RegisterTotal))
	data.Set("recharge_amount", convert.ToString(info.RechargeAmount))
	data.Set("recharge_count", convert.ToString(info.RechargeCount))
	data.Set("date", convert.ToString(info.Date))
	data.Set("create_at", convert.ToString(info.CreateAt))
	data.Set("updated_at", convert.ToString(info.UpdatedAt))

	querySql, values := parseData.FormatAddSql("promotion_link_data_statistics", data)
	querySql = fmt.Sprintf("%s %s", querySql, cond)

	//cond 参数
	values = append(values, info.RegisterTotal)
	values = append(values, info.DownloadTotal)
	values = append(values, info.ClickTotal)
	values = append(values, info.RechargeAmount)
	values = append(values, info.RechargeCount)
	values = append(values, info.UpdatedAt)

	if _, err := db.MqDB().Exec(querySql, values...); err != nil {
		log.Err(fmt.Sprintf("sql:%v values:%v %+v", querySql, values, err))
	}
}
